<!--
@description    绩效考核报表
@author         秦俊强
@email          458112865@qq.com
@create         2020-04-05 13:00
-->

<template>
  <a-card :bordered="false">

    <!-- 查询 start -->
    <div class="table-page-search-wrapper">
      <a-row :gutter="24">
        <a-col :md="14" :sm="8">
          <span>考核期：</span>
          <a-select v-if="!yearMonthList.loading"
                    :value="yearMonthList.val.text" @change="changeDate">
            <a-select-option v-for="date in yearMonthList.arr"
                             :key="date.value">{{ date.text }}</a-select-option>
          </a-select>
          <a-select v-else :defaultValue="'数据加载中'" disabled></a-select>
        </a-col>

        <a-col :md="10" :sm="8">
          <div class="table-operator">
            <a-button type="primary" icon="history" :disabled="timeout"
                      @click="reportCreator()">生成当期（{{ yearMonthList.val.text }}）报表</a-button>
          </div>
        </a-col>
      </a-row>
    </div>
    <!-- 查询&编辑 end -->


    <!-- table区域-begin -->
    <div class="container-box">
      <!-- 表格内容 -->
      <a-table bordered :loading="loading"
               :columns="tableData.columns"
               :dataSource="tableData.dataSource"
               :scroll="tableData.tableScroll"
               :pagination="false">

        <!-- 审核状态 start -->
        <template slot="auditStatus" slot-scope="text">
          <div v-if="text === '0'">
            <a-icon type="check-circle" theme="filled" style="color: #14BA89;" />
            <span> 初审通过</span>
          </div>

          <div v-else-if="text === '1'">
            <a-icon type="pause-circle" theme="filled" style="color: #FF6600;" />
            <span> 待申请</span>
          </div>

          <div v-else-if="text === '2'">
            <a-icon type="pause-circle" theme="filled" style="color: #FF6600;" />
            <span> 审核中</span>
          </div>

          <div v-else-if="text === '3'">
            <a-icon type="check-circle" theme="filled" style="color: #14BA89;" />
            <span> 已审核</span>
          </div>

          <div v-else-if="text === '4'">
            <a-icon type="pause-circle" theme="filled" style="color: #FF6600;" />
            <span> 已退回</span>
          </div>

          <div v-else>
            <a-icon type="minus-circle" theme="filled" style="color: #F1523A;" />
            <span> 审核状态异常</span>
          </div>
        </template>
        <!-- 审核状态 end -->

        <!-- 生成状态 start -->
        <template slot="reportStatus" slot-scope="text">
          <div v-if="text === '0'">
            <a-icon type="minus-circle" theme="filled" style="color: #F1523A;" />
            <span> 异常</span>
          </div>

          <div v-else-if="text === '1'">
            <a-icon type="pause-circle" theme="filled" style="color: #FF6600;" />
            <span> 待生成</span>
          </div>

          <div v-else-if="text === '2'">
            <a-icon type="loading" style="color: #FF6600;" />
            <span> 生成中...</span>
          </div>

          <div v-else-if="text === '3'">
            <a-icon type="check-circle" theme="filled" style="color: #14BA89;" />
            <span> 已生成</span>
          </div>

          <div v-else>
            <a-icon type="minus-circle" theme="filled" style="color: #F1523A;" />
            <span> 生成状态异常</span>
          </div>
        </template>
        <!-- 生成状态 end -->

        <!-- 操作 -->
        <template slot="action" slot-scope="text, record, ind">
          <!-- 只有审核通过，并且是已经生成的报表才可操作 -->
          <div>
            <span class="edit" v-if="['0', '3'].indexOf(record.auditStatus) >= 0"
                  @click="reportCreator(record.reportCode, ind)">
              {{ record.reportStatus === '3' ? '重新生成' : '生成报表' }}
            </span>
            <span v-else style="color: #cccccc;">
              {{ record.reportStatus === '3' ? '重新生成' : '生成报表' }}
            </span>

            <!-- 分割线 -->
            <a-divider type="vertical" />

            <span class="edit" v-if="record.reportStatus === '3'"
                  @click="exportReport(record, ind)">下载报表</span>
            <span v-else style="color: #cccccc;">下载报表</span>
          </div>
        </template>
      </a-table>
    </div>

  </a-card>
</template>



<script>
  /* 封装通用 api 服务 */
  import { apiService } from '@/api/api.service.js';

  /**
   * api 接口
   *
   * getYearMonthList => 获取可选考核期
   * getReportList => 获取绩效考核报表列表
   * reportCreator => 生成绩效考核报表
   * exportReport => 下载考核报表
   * */
  import { getYearMonthList, getReportList, reportCreator, exportReport } from '@/api/api.js'
  import { downFile } from '@/api/manage';




  export default {
    data () {
      return {
        loading: true,

        /* 年月下拉菜单 */
        yearMonthList: {
          loading: true,
          arr: [],    // 可选择的年月列表
          val: {}     // 已选年月，默认数组第 0 个
        },

        /* 配置表格 */
        tableData: {
          columns: [{
            title: '报表名称',
            align: 'center',
            dataIndex: 'reportName'
          }, {
            title:'报表生成时间',
            align: 'center',
            dataIndex: 'reportDate'
          }, {
            title:'最近一次下载时间',
            align: 'center',
            dataIndex: 'downloadDate'
          }, {
            title:'下载次数',
            align: 'center',
            dataIndex: 'downloadTimes'
          }, {
            title:'审核状态',
            align: 'center',
            dataIndex: 'auditStatus',
            scopedSlots: { customRender: 'auditStatus' }
          }, {
            title:'生成状态',
            align: 'center',
            dataIndex: 'reportStatus',
            scopedSlots: { customRender: 'reportStatus' }
          }, {
            title: '操作',
            dataIndex: 'action',
            align: 'center',
            fixed: 'right',
            width: 200,
            scopedSlots: { customRender: 'action' }
          }],
          dataSource: []
        },

        /* 定时器 */
        timeout: false
      }
    },

    created() { this.getYearMonthList(); },

    methods: {

      /* 监听考核期变化 */
      changeDate(code) {
        let arr = this.yearMonthList.arr;
        this.yearMonthList.val = arr.find((item) => { return (item.value === code); });
        this.loading = true;
        if (this.timeout) { return; }
        this.getReportList();
      },

      /* 生成当期报表 */
      reportCreator(code, ind) {
        let param = {
          indexYearMonth: this.yearMonthList.val.value,
          reportCode: code || ''
        };
        if (typeof ind === 'number') { this.tableData.dataSource[ind].reportStatus = '1'; }
        apiService(reportCreator(param)).then((res) => {
          if (this.timeout) { return; }

          this.timeout = true;
          this.getReportList();
        }).catch((error) => {
          this.tableData.dataSource[ind].reportStatus = '0';
          this.$message.error(error.message);
        });
      },

      /* 获取绩效考核报表列表 */
      getReportList() {
        let param = {
          indexYearMonth: this.yearMonthList.val.value
        };
        if (!this.timeout) { this.loading = true; }
        apiService(getReportList(param)).then((res) => {
          this.loading = false;
          let result = res.result;
          this.tableData.dataSource = result.records;

          /* auditStatus => 0:已初审; 1:待申请; 2:审核中; 3:已终审; 4:已退回; */
          /* reportStatus => 0: 异常; 1:待生成; 2:生成中; 3:已生成 */
          if (result.records.some(item => ['0', '3'].indexOf(item.auditStatus) < 0 || item.reportStatus === '2')) {
            this.timeout = true;
            setTimeout(() => { this.getReportList(); }, 5 * 1000);
          } else {
            this.timeout = false;
          }
        }).catch((error) => {
          this.loading = false;
          this.$message.error(error.message);

          if (this.timeout) { this.getReportList(); }
        });
      },

      /* 获取可选考核期下拉菜单 */
      getYearMonthList() {
        apiService(getYearMonthList()).then((res) => {
          let list = res.result || [];
          this.yearMonthList = {
            loading: false,
            arr: list || [],
            val: list[0] || {}
          };

          this.getReportList();
        }).catch((error) => {
          this.yearMonthList.loading = false;
          this.$message.error(error.message);
        });
      },

      /* 下载当前某一项报表 Excel 文件在本地 */
      exportReport(report){
        let fileName = report.reportName;
        let param = {
          indexYearMonth: this.yearMonthList.val.value,
          reportCode: report.reportCode,
          isTotal: false
        }

        downFile('/api/pms/report/exportXlsx', param).then((data) => {
          if (!data) {
            this.$message.error("文件下载失败");
            return;
          }

          let name = fileName + '-' + this.yearMonthList.val.value;
          if (typeof window.navigator.msSaveBlob !== 'undefined') {
            window.navigator.msSaveBlob(new Blob([data]), name + '.xlsx');
          } else {
            let url = window.URL.createObjectURL(new Blob([data]));
            let link = document.createElement('a');
            link.style.display = 'none';
            link.href = url;
            link.setAttribute('download', name + '.xlsx');
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);    // 下载完成移除元素
            window.URL.revokeObjectURL(url);    // 释放掉 blob 对象
          }

          // this.getReportList();
        }).catch((error) => {
          this.$message.error(error.message);
        });
      }

    }
  }
</script>


<style lang="less" scoped>
  /deep/.table-page-search-wrapper {
    margin-bottom: 10px;
  }
  /deep/.table-operator {
    float: right;
    margin-bottom: 0;
    button { margin-right: 0; margin-left: 8px; }
  }

  .container-box {
    /deep/.ant-alert { padding-left: 15px; }

    .edit, .count { color: @primary-color; }
    .edit { cursor: pointer; }
    .count { font-weight: bold; }
  }
</style>
